package com.example.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.example.dao.BookDao;
import com.example.domain.Book;
import com.example.util.Page;
@Component
public class BookDaoImpl implements BookDao {
  
	@PersistenceContext
	EntityManager entityManager;
	@Transactional
	public void save(Book book) {
		try{
			/**
			 * merge,persist区别
			 * merge 如果数据不存在，插入，如果存在，更新
			 * persist 如果数据不存在，插入，存在，抛异常
			 * */
			entityManager.merge(book);
			//entityManager.persist(book);
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	public Book get(String id) {
		return entityManager.find(Book.class, id);
	}
	@Override
	public void getBycontain(Page<Book> page) {
		TypedQuery<Book> query=entityManager.createQuery("select o from Book o",Book.class);
		query.setFirstResult(page.getCurrentPageNo()*page.getMaxResult());
		query.setMaxResults(page.getMaxResult());
		
		List<Book> booklist=query.getResultList();
		page.setList(booklist);
		TypedQuery<Long> total=entityManager.createQuery("select count(o) from Book o",Long.class);
		page.setTotalResult(total.getSingleResult().intValue());
		
	}
	@Override
	public void update(Book book) {
		entityManager.merge(book);
		entityManager.flush();
	}

}
